package com.dhl.springbootrabbitmq.controller;


import com.dhl.springbootrabbitmq.config.ConfirmConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author danghailiang
 * 高级篇消息确认机制
 */
@Slf4j
@RestController
@RequestMapping("/confirm")
public class ConfirmSendMsgController {
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 模拟交换机宕机
     * @param msg 消息
     */
    @GetMapping("/sendMsg/{msg}")
    public void sendMsg(@PathVariable String msg) {
        log.info("接收到的消息：{},开发转发给路由;", msg);
        CorrelationData correlationData = new CorrelationData("107206");
        rabbitTemplate.convertAndSend(ConfirmConfig.CONFIRM_EXCHANGE_NAME,ConfirmConfig.CONFIRM_ROUTING_KEY,msg.getBytes(StandardCharsets.UTF_8),correlationData);
        rabbitTemplate.convertAndSend(ConfirmConfig.CONFIRM_EXCHANGE_NAME+":模拟交换宕机",ConfirmConfig.CONFIRM_ROUTING_KEY,(msg+":模拟宕机消息").getBytes(StandardCharsets.UTF_8),correlationData);
    }

    /**
     * 模拟队列宕机
     * @param msg 消息
     */
    @GetMapping("/sendMsgRouting/{msg}")
    public void sendMsgRouting(@PathVariable String msg) {
        log.info("接收到的消息：{},开发转发给路由;", msg);
        CorrelationData correlationData = new CorrelationData("107206");
        rabbitTemplate.convertAndSend(ConfirmConfig.CONFIRM_EXCHANGE_NAME,ConfirmConfig.CONFIRM_ROUTING_KEY,msg.getBytes(StandardCharsets.UTF_8),correlationData);
        rabbitTemplate.convertAndSend(ConfirmConfig.CONFIRM_EXCHANGE_NAME,ConfirmConfig.CONFIRM_ROUTING_KEY+":模拟队列宕机",(msg+":模拟宕机消息").getBytes(StandardCharsets.UTF_8),correlationData);
    }

    /**
     * 模拟队列宕机，发送给备用交换和备用队列
     * @param msg 消息
     */
    @GetMapping("/sendMsgBackup/{msg}")
    public void sendMsgBackup(@PathVariable String msg) {
        log.info("接收到的消息：{},开发转发给交换;", msg);
        CorrelationData correlationData = new CorrelationData("107206");
        rabbitTemplate.convertAndSend(
                ConfirmConfig.CONFIRM_EXCHANGE_NAME,
                ConfirmConfig.CONFIRM_ROUTING_KEY,
                msg.getBytes(StandardCharsets.UTF_8),
                correlationData);
        rabbitTemplate.convertAndSend(
                ConfirmConfig.CONFIRM_EXCHANGE_NAME,
                ConfirmConfig.CONFIRM_ROUTING_KEY+":模拟队列宕机",
                (msg+":这是一条发送备用消息").getBytes(StandardCharsets.UTF_8),
                correlationData);
    }
}
